import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:yqmssa_app/config/app_config.dart';
import 'package:yqmssa_app/config/get_devide_info.dart';
import 'package:yqmssa_app/router/page_router.dart';
import 'package:yqmssa_app/utils/check_utils.dart';
import 'package:yqmssa_app/utils/shared_utils.dart';
import 'package:yqmssa_app/utils/tencent_im_utils.dart';
import 'package:yqmssa_app/widget/alert_widget.dart';
import 'package:get/get.dart';

import 'app_dl_request.dart';

class LoginManager extends GetxController {
  final isRead = false.obs;

  final phone = TextEditingController();
  final code = TextEditingController();
  final phoneFocus = FocusNode();
  final codeFocus = FocusNode();

  final codeText = "获取验证码".obs;

  int seconds = 60;

  Timer? _timer;

  void startUp() {
    if (seconds >= 0 && seconds < 60) return;
    _timer = Timer.periodic(const Duration(seconds: 1), (time) {
      seconds--;
      codeText.value = "$seconds秒后重新获取";
      if (seconds == 0) {
        _timer?.cancel();
        seconds = 60;
        codeText.value = "获取验证码";
      }
    });
  }

  @override
  onInit() {
    super.onInit();
    if (AppConfig.channel != "huawei") {
      activation();
    }
  }

  ///激活
  activation() async {
    final oaID = await GetDeviceInfo.getOaID();
    final imei = await GetDeviceInfo.getImei();
    final putData = {"imei": imei, "oaid": oaID};
    AppDlRequest.activation(putData);
  }

  void sendCode() {
    if (CheckUtils.phoneCheck(phone.text).isNotEmpty) {
      SmartDialog.showToast(CheckUtils.phoneCheck(phone.text));
      return;
    }
    SmartDialog.showLoading(msg: "发送验证码中...");
    AppDlRequest.sendPhoneCode(phone.text).then((value) {
      SmartDialog.dismiss();
      startUp();
    }).catchError((err) {
      SmartDialog.dismiss();
    });
  }

  void appLogin() async {
    if (CheckUtils.phoneCheck(phone.text).isNotEmpty) {
      SmartDialog.showToast(CheckUtils.phoneCheck(phone.text));
      return;
    }
    if (code.text.isEmpty) {
      SmartDialog.showToast("请输入验证码");
      return;
    }

    if (code.text.length < 6) {
      SmartDialog.showToast("验证码格式不正确");
      return;
    }
    if (!isRead.value) {
      readAgreement();
      return;
    }
    final oaID = await GetDeviceInfo.getOaID();
    final imei = await GetDeviceInfo.getImei();
    final putData = {
      'phone': phone.text,
      'captcha': code.text,
      'imei': imei,
      'oaid': oaID,
    };
    SmartDialog.showLoading(msg: "登录中...");
    if (AppConfig.channel == "huawei") {
      activation();
    }
    AppDlRequest.appLogin(putData).then((value) {
      sharedUtils.userPhone = phone.text;
      sharedUtils.token = value.token;
      sharedUtils.havePop = value.havePop;
      AppConfig.appInitData.loginReplaceData(value.toJson());
      SmartDialog.dismiss();
      tencentImUtils.getSign(() {
        Get.offNamed(PageRouter.index);
      });
    }).catchError((err) {
      SmartDialog.dismiss();
    });
  }

  void readAgreement() {
    Get.dialog(
      MyAlertWidget(
        title: "登录提示",
        content: Padding(
          padding: const EdgeInsets.all(8.0),
          child: RichText(
            textAlign: TextAlign.center,
            text: TextSpan(
              style: const TextStyle(color: Color(0XFF666666)),
              children: [
                const TextSpan(text: "为了更好地保障您的合法权益，请您阅读并同意一下协议"),
                WidgetSpan(
                    child: InkWell(
                        onTap: () {
                          Get.toNamed(PageRouter.agreement, parameters: {"title": "注册协议", "url": AppConfig.xieYIData.userAgreementUrl});
                        },
                        child: const Text(
                          "《注册协议》",
                          style: TextStyle(color: Color(0XFFE4B591)),
                        ))),
                WidgetSpan(
                    child: InkWell(
                        onTap: () {
                          Get.toNamed(PageRouter.agreement, parameters: {"title": "隐私政策", "url": AppConfig.xieYIData.privacyAgreementUrl});
                        },
                        child: const Text(
                          "《隐私政策》",
                          style: TextStyle(color: Color(0XFFE4B591)),
                        ))),
              ],
            ),
          ),
        ),
        onConfirm: () {
          isRead.value = true;
        },
      ),
    );
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }
}
